package org.abettor.util.security.cert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

/**
 * 证书管理类工厂
 * @author <a href="http://www.abettor.org/" target="_blank">abettor</a>
 * @deprecated
 */
public class SpecificTrustManagerFactory
{
	private String alg;
	private String keyStoreName;
	private String keyStorePass;

	/**
	 * 构造函数
	 * @param keyStoreName 要使用的证书名称
	 * @param keyStorePass 验证证书存储区完整性的密码
	 */
	public SpecificTrustManagerFactory(String keyStoreName, String keyStorePass)
	{
		alg = TrustManagerFactory.getDefaultAlgorithm();
		this.keyStoreName = keyStoreName;
		this.keyStorePass = keyStorePass;
	}

	/**
	 * 构造函数
	 * @param keyStoreName 要使用的证书名称
	 * @param keyStorePass 验证证书存储区完整性的密码
	 * @param alg 加密算法名
	 */
	public SpecificTrustManagerFactory(String keyStoreName, String keyStorePass, String alg)
	{
		this.alg = alg;
		this.keyStoreName = keyStoreName;
		this.keyStorePass = keyStorePass;
	}

	/**
	 * 设定加密算法
	 * @param alg 加密算法名称
	 */
	public void setAlgorithm(String alg)
	{
		this.alg = alg;
	}

	/**
	 * 取得TrustManager对象
	 * @return 证书中包含的TrustManager对象
	 * @throws KeyStoreException 获取证书存储实例失败抛出此异常
	 * @throws NoSuchAlgorithmException keyStoreName所指定的证书算法异常
	 * @throws CertificateException keyStorePass错误抛出此异常
	 * @throws FileNotFoundException keyStoreName所指定的文件不存在抛出此异常
	 * @throws IOException 读取keyStoreName所指定的文件失败抛出此异常
	 */
	public TrustManager [] getTrustManagers()
	throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException
	{
		//	获取Java默认的证书存储区实例
		KeyStore ks = KeyStore.getInstance("JKS");
		if(ks == null)
		{
			return null;
		}

		//	加载证书
		if(keyStorePass != null)
		{
			char [] keyStorePassArray = keyStorePass.toCharArray();
			ks.load(new FileInputStream(keyStoreName), keyStorePassArray);
		}
		else
		{
			ks.load(new FileInputStream(keyStoreName), null);
		}

		//	创建TrustManager工厂并用存储区将其初始化
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(alg);
		tmf.init(ks);

		return tmf.getTrustManagers();
	}
}
